package org.visionlibrary.image.filters.thresholding;

import java.awt.Point;
import java.util.Random;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.model.WindowFilter;


public class AdaptiveRandomNoiseHalftone extends WindowFilter {
	protected int width;
	protected int height;

	private double percentage = 10;
	
	public double getPercentage() {
		return percentage;
	}

	public void setPercentage(double percentage) {
		if(percentage <= 100 && percentage >= 0)
			this.percentage = percentage;
	}
	
	public AdaptiveRandomNoiseHalftone(int height, int width) {
		this.height = height;
		this.width = width;
	}

	public AdaptiveRandomNoiseHalftone() {
		this(3,3);
	}

	@Override
	protected int getNewPixelVal(TiledImage src, Point p, int channel) {
		int value = 0;
		int count = 0;

		Point pIter = new Point();
		for (pIter.y = 0; pIter.y < windowHeight; pIter.y++)
			for (pIter.x = 0; pIter.x < windowWidth; pIter.x++) {
				int val = getWindowPixelVal(src, pIter, channel);
				value += val;
				count++;
			}

		int mean = value / count;
		
		int high = (int)((percentage*mean)/100.0d);
		int low = -high;
		
		int currentPixelVal = getWindowPixelVal(src, dstPointInWindow, channel);
		double noise = (new Random()).nextInt(high - low + 1) + low;
		
		if(currentPixelVal <= mean + noise)
			return 0;
		else
			return 255;
	}

	@Override
	protected void setWindowProperties() {
		windowWidth = width;
		windowHeight = height;
		dstPointInWindow = new Point(width / 2, height / 2);
	}
}
